<?php
use app\we\sdk\Thinkwechat;
use app\we\sdk\Wechat;
use app\we\sdk\ErrCode;
// use app\we\sdk\Auth;


// 从微信获取用户信息
// public function myinfo()
function we_init($appid)
 {
        
    $options = model('we/We')->info($appid);
    $weObj = new Thinkwechat($options);
    $weObj->options=$options;
   
    return $weObj;
}

function we_error($weObj,$res='')
{
    // TODO::可能要发送邮件，并且记录错误
    if (!$res) {
        $error=ErrCode::getErrText($weObj->errCode);
        mylog($error);
        return $error;
    }

    return;
}


// 从微信获取用户信息
// public function myinfo()
function get_user_info($appid,$openid)
 {

    $weObj=we_init($appid);
    $fans=$weObj->getUserInfo($openid );
     
    we_error($weObj,$fans);
    
    if ($fans){
      $fans['appid']=$appid;
      $fans['aid']=$weObj->options['aid'];  
    } 
    
    return $fans;
}

/**
 * 发送客服消息
 * 可以直接发送一个机器人功能id
 * 可以原生数组方式发送
 * @return boolean true-成功，false-失败
 * @author $this <498944516@qq.com>
 */
function custom_message($to,$answer)
 { 
    $fans=model('we/WeFans')->info($to);
    if (!is_array($answer)){ 
    //如果是机器人消息,带上必要的用户信息去获取机器人
    $data['fans']=$fans;
    $data['appid']=$fans['appid'];
    if (is_numeric($answer)){  //兼容默认为文字消息
    $reply=model('Rob/RobAnswer')->infoByMap(['id'=>$answer],$data);
    }else{
    $reply['type']="text";
    $reply['message']=$answer;
    }

    $reply['touser']=$fans['openid'];
    $reply['msgtype']=$reply['type'];

    //将机器人返回格式化成客服消息内容
    switch ($reply['type']) {
        case 'text':
             $reply['text']=['content'=>$reply['message']];
             break;
        case 'image':
             $reply['image']=['media_id'=>$reply['message']];
             break;
        case 'news':
        //腾讯有病，这里键值和其他消息不一致，所以全部转小写
             foreach ($reply['message'] as $key => &$value) {
                $value=array_change_key_case($value);
             }
             $reply['news']=['articles'=>$reply['message']];
             break;
         
         default:
             # code...
             break;
     }
    }else{
       $reply=$answer;
       $reply['touser']=$fans['openid'];
    }
   
   
     $weObj=we_init($fans['appid']);
     $ret=$weObj->checkAuth();
     $res=$weObj->sendCustomMessage($reply); 
     $error=we_error($weObj,$res);

     //记录发送日志
     $message=[
     'aid'=>$fans['aid'],
     'appid'=>$fans['appid'],
     'nickname'=>$fans['nickname'],
     'ToUserName'=>$fans['openid'],
     'FromUserName'=>'customMessage',
     'CreateTime'=>time(),
     'MsgType'=>$reply['msgtype'],
     'status'=>0
     ];
    
     model('we/WeMessage')->saveMessage($message);
     return $error;
}


     /**
     * sendTemplateMessage  发送模板消息
     * @author:$this 498944516@qq.com
     * $reply=[
       template_id'=>'LsIc21raK3kWuX8j8hgBwJ-1cWn35PIdxgz2KMxgMPQ',
      'url'=>'http://baidu.com',
      'data'=>[
      'first'=>['value'=>'你好'],
      'keyword1'=>['value'=>'你好'],
      'remark'=>['value'=>'你好']
      ]
      ];
     */
 function template_message($to,$data)
    {
      
        $fans=model('we/WeFans')->info($to);
        $reply['touser'] = $fans['openid'];
        $reply['template_id']=$data['template_id'];
        $reply['url']=$data['url'];
        $reply['data']=$data['data'];
       
        $weObj=we_init($fans['appid']);
        $res=$weObj->checkAuth();
        $res=$weObj->sendTemplateMessage($reply); 
        we_error($weObj,$res);

        //记录发送日志
        $message=[
             'aid'=>$fans['aid'],
             'appid'=>$fans['appid'],
             'nickname'=>$fans['nickname'],
             'ToUserName'=>$fans['openid'],
             'FromUserName'=>'templateMessage',
             'CreateTime'=>time(),
             'MsgType'=>'templateMessage',
             'status'=>0
             ];
        
         model('we/WeMessage')->saveMessage($message);
         
        return true;
    }

    /**
     * sendGroupMassMessage  群发消息
     * @author:$this 498944516@qq.com
     * $reply=[
       filter'=>["is_to_all"=>False,  "group_id"=>"2" ],
        mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
     * text => array ( "content" => "hello")
     */
 function send_group_mass_message($appid,$reply)
    {
        
        $reply=[
        'filter'=>['is_to_all'=>true],
        "msgtype"=>"text",
        'text'=>['content'=>'hello wechat']
        ];

        $weObj=we_init($appid);
        $options=$weObj->options;
        $res=$weObj->checkAuth();
        $res=$weObj->sendGroupMassMessage($reply); 
        we_error($weObj,$res);

        //记录发送日志
        $message=[
             'aid'=>$options['aid'],
             'appid'=>$options['appid'],
             'nickname'=>'sendGroupMassMessage',
             'ToUserName'=>'sendGroupMassMessage',
             'FromUserName'=>'sendGroupMassMessage',
             'CreateTime'=>time(),
             'MsgType'=>'sendGroupMassMessage',
             'status'=>0
             ];
        
         model('we/WeMessage')->saveMessage($message);
         
        return true;
    }

     //生成二维码  getQRCode($appid,1);
    function get_qrcode($appid,$type=0,$scene_id='',$expire=604800)
    {
        $weObj=we_init($appid);
        $res=$weObj->checkAuth();
        
       
        //如果不是scene_str 则自动获取id
        if ($type==0 or $type==1) $scene_id=model('WeSceneQrcode')->autoScene_id($appid,$type);
       
        $qrcode=$weObj->getQRCode($scene_id,$type,$expire);
        
        $qrcode['url']=$weObj->getQRUrl($qrcode['ticket']);
        we_error($weObj,$qrcode['url']);
        //创建短链接
        $qrcode['short_url'] = get_short_url($appid,$qrcode['url']);
        
        //补充必要信息
        $qrcode['appid'] =$appid;
        $qrcode['qrcode_type'] =$type;
        if ($type==2){
            $qrcode['scene_str'] =$scene_id;
        }else{
            $qrcode['scene_id'] =$scene_id;
        }
        if ($type==0) $qrcode['expire'] =$expire;

      
        return $qrcode;
    }

    //创建短网址
    function get_short_url($appid,$long)
    {
        $weObj=we_init($appid);
        $res=$weObj->checkAuth();
        
        $short=$weObj->getShortUrl($long);
        we_error($weObj,$short);
       
        return $short;
    }


     //同步菜单
    function send_menu($appid,$my_menu)
    {
        
        $weObj=we_init($appid);
        $res=$weObj->checkAuth();
     
        if(isset($my_menu['matchrule'])){
        $res=$weObj->addconditionalMenu($my_menu);
        }else{
        $res=$weObj->createMenu($my_menu);
        }
        $error=we_error($weObj,$res);
       
        return $error;
    }

      //获取菜单
    function get_menu($appid)
    {
        $weObj=we_init($appid);
        $res=$weObj->checkAuth();
        
        $menu=$weObj->getMenu();
        $error=we_error($weObj,$menu);
     
       
        return $menu;
    }

      //获取素材
    function get_media($appid,$MediaId)
    { 
        $weObj=we_init($appid);
        $res=$weObj->checkAuth();
        
        $pic = $weObj->getMedia($MediaId);
        $error=we_error($weObj,$pic);
    
        return $pic;
    }

      //上传素材
    function upload_media($appid,$pic,$type='image')
    { 
        $weObj=we_init($appid);
        $res=$weObj->checkAuth();
        
        set_time_limit(0);

        if (is_numeric($pic)){
            $path=$_SERVER["DOCUMENT_ROOT"].'/'. ($type=='image'?get_cover($pic,'path'):get_file($pic));
        }else{
            $path=$_SERVER["DOCUMENT_ROOT"].'/'.$pic;
        }
       
        $path=array('media'=>'@'.$path);
     
        $media=$weObj->uploadMedia($path,$type); 
       
        $error=we_error($weObj,$media);
       
        return $media;
     
    }

     //获取卡券
    function get_cards($appid)
    { 
        
        $weObj=we_init($appid);
        $res=$weObj->checkAuth();
        
        $list = $weObj->getCardIdList();

        $error=we_error($weObj,$list);
        $cards=$list['card_id_list'];
        return $cards;
       
    }

    function get_card($appid,$card_id)
    { 
         $weObj=we_init($appid);
         $res=$weObj->checkAuth();
         $card=$weObj->getCardInfo($card_id);
         $error=we_error($weObj,$card);
         return $card;
    }

    function get_fans_card($appid,$openid)
    { 
         $weObj=we_init($appid);
         $res=$weObj->checkAuth();
         $cards=$weObj->getUserCardList($openid);
         $error=we_error($weObj,$cards);
         return $cards;
    }



      //注册jssdk
    function jssdk($appid)
    { 
        $weObj=we_init($appid);
        $res=$weObj->checkAuth();
        
        $js_ticket = $weObj->getJsTicket();
        $error=we_error($weObj,$js_ticket);
        $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $myjssdk = $weObj->getJsSign($url);
        $error=we_error($weObj,$myjssdk);
        return $myjssdk;
    }

       //auth登录
    function auth($appid='wxea877923bf435db8')
    { 
        $options = model('we/We')->info($appid);
        $auth = new Auth( $options);
        return $auth->wxuser;
    }


    /**
 * 获取微信支付参数
 * @author 艾逗笔<765532665@qq.com>
 */
    function get_jsapi_parameters($pay=['appid'=>'wxea877923bf435db8']) {
       
        ini_set('date.timezone','Asia/Shanghai');
        vendor('paysdk.lib.WxPay#Api');
        vendor('paysdk.example.WxPay#JsApiPay');
        vendor('paysdk.example.log');

        //初始化日志
        $logHandler= new CLogFileHandler(date('Y-m-d').'.log');
        $log = Log::Init($logHandler, 15);

       
        $options = model('we/We')->info($pay['appid']);

        //①、获取用户openid
        $tools = new JsApiPay();
        $openId = $tools->GetOpenid();

        //②、统一下单
        $input = new WxPayUnifiedOrder();
        $input->SetBody($pay['product']);
        $input->SetAttach($pay['description']);
        $input->SetOut_trade_no(WxPayConfig::MCHID.date("YmdHis"));
        $input->SetTotal_fee($pay['price']*100);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag($pay['product']);
        $input->SetNotify_url("http://paysdk.weixin.qq.com/example/notify.php");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = WxPayApi::unifiedOrder($input);
       
       
        $jsApiParameters = $tools->GetJsApiParameters($order);

        //获取共享收货地址js函数参数
        $editAddress = $tools->GetEditAddressParameters();

        //③、在支持成功回调通知中处理成功之后的事宜，见 notify.php
        /**
         * 注意：
         * 1、当你的回调地址不可访问的时候，回调通知会失败，可以通过查询订单来确认支付是否成功
         * 2、jsapi支付时需要填入用户openid，WxPay.JsApiPay.php中有获取openid流程 （文档可以参考微信公众平台“网页授权接口”，
         * 参考http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html）
         */
       
        return $jsApiParameters;
    }

    function we_replace($string='',$data=[]){
      
        // TODO::这里要区分企业号和微信号从而提高效率
        if (empty($data)) return $string;
        if (isset($data['aid'])){
         $jituan=model('admin/AdminAdmin')->info($data['aid']);
        }

        if (isset($data['shopid'])){
         $shop=model('admin/AdminShop')->info($data['shopid']);   
        }

        $replaces=[
        // 系统相关
        '{当前日期}'=>date('Y-m-d',time()),
        '{当前时间}'=>date('Y-m-d H:i:s',time()),
        // 特殊字符
        '</br>'=>"\n",
        '<br/>'=>"\n",
        '</p>'=>"\n",
        // 粉丝相关
        '{粉丝ID}'=>$data['fans']['id'],
        '{粉丝OPENID}'=>$data['fans']['openid'],
        '{粉丝昵称}'=>$data['fans']['nickname'],
       
         // 微信设置相关
         
        ];

        if(isset($jituan)){
             // 组织相关
        $replace['{企业名称}']=$jituan['title'];
        }
        if(isset($shop)){
        $replace['{分店名称}']=$shop['title'];
        $replace['{大众点评店铺编号}']=$shop['dazhong_shopid'];
        $replace['{WIFI}']=$shop['wifi'];
        
        }


        // 循环替换
        foreach ($replaces as $key => $replace) {
           $string=str_replace($key,$replace, $string);
        }
        return $string;
     }


    

   


    

    





